/**
 * @file filter
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {Renderer} from '../../renderer';
import * as assign from 'object-assign';
import * as moment from 'moment';

const DefaultProps = {
  date: {
    format: 'LL'
  },

  datetime: {
    format: 'LLL'
  },

  time: {
    format: 'LT'
  },

  'date-range': {
    format: 'LL',
    delimiter: ' - '
  }
};

@Renderer({
  name: 'field-date',
  desc: '...',
  test: /(?:^|\/)field\/(?:date|datetime|time|date-range)$/,
  filter: (config, path) => {
    const type = path.split('/').pop();
    return assign({}, DefaultProps[type || 'date'], config);
  }
})
export default class DateField extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    type: PropTypes.string.isRequired,
    placeholder: PropTypes.string,
    format: PropTypes.string
  };

  static defaultProps = {
    placeholder: '-',
    format: 'LLL',
    delimiter: ' - ',
    valueFormat: 'X'
  };

  formatValue(value) {
    const {
      format,
      delimiter,
      valueFormat,
      $path
    } = this.props;

    const type = $path.split('/').pop();

    if (type === 'date-range') {
      if (typeof value === 'string') {
        const parts = value.split(delimiter);
        value = {
          startDate: parts[0],
          endDate: parts[1]
        }
      }

      return moment(value.startDate, valueFormat).format(format) + delimiter
        + moment(value.endDate, valueFormat).format(format);
    } else {
      return moment(value, valueFormat).format(format);
    }
  }

  render() {
    const {
      className,
      value,
      placeholder
    } = this.props;

    let body = value && value != '0' ? this.formatValue(value) : placeholder && <span className="text-muted">{placeholder}</span>;

    return (
      <span className={className}>
        {body}
      </span>
    );
  }
}
